<template>
  <page-header-wrapper :title="false">
    <a-card title="执照业务列表">
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          :model="queryParam"
        >
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="合同编号">
                <a-input v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号" :allowClear="true" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="业务编号">
                <a-input v-model="queryParam['filter[business_no]']" placeholder="请输入业务编号" :allowClear="true"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="流程状态">
                  <a-select v-model="queryParam['filter[status2]']" placeholder="请选择业务状态" :allowClear="true">
                    <a-select-option v-for="(item,index) in statusOpts" :key="index" :value="index">{{item}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="开启时间">
                  <a-range-picker v-model="queryParam['open_time_start']" @change="onChangeTime" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所属顾问">
                  <a-input v-model="queryParam['filter[username]']" placeholder="请输入所属顾问" :allowClear="true" />
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {}">
                  <a-button type="primary" @click="$refs.table.refresh(true)">搜索</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'" />
                  </a>
                </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="table-operator">
        <s-table
          bordered
          ref="table"
          :row-key="(record) => record.cb_id"
          :columns="licenseColumns"
          :data="licenseData"
        >
          <template slot="contract_no" slot-scope="text,record">
            <a-popover trigger="hover">
              <template slot="content">
                <p>合同编号：{{text}}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="text" type="copy" @click="copy" /></p>
                <p>业务编号：{{record.business_no}}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="record.business_no" type="copy" @click="copy" /></p>
              </template>
              {{text}}<br>
              <a @click="handleButtonClick(record.cb_id)">{{record.business_no}}</a>
            </a-popover>
          </template>
          <template slot="adviser" slot-scope="text, record">
            <a-tag>{{text}}</a-tag><br>
            <a-tag>{{record.group_type}}组</a-tag><br>
            <a-tag>{{record.leader}}</a-tag>
          </template>
          <template slot="status2" slot-scope="text, record">
            <a-button icon="edit" v-if="record.status2_code == '20' || record.status2_code == '22'" size="small" type="danger" @click="changeStatus(record.cb_id)">{{text}}</a-button>
            <a-button v-else size="small" type="primary" @click="changeStatus(record.cb_id)">{{text}}</a-button>
          </template>
          <template slot="history" slot-scope="text, record">
            <a @click="historyModal(record.cb_id)">{{text}}</a>
          </template>
          <template slot="mat_filename" slot-scope="text, record">
            <a @click="download (record.mat, text)">{{text}}</a>
          </template>
          <template slot="action" slot-scope="text,record">
            <a-button size="small" type="primary" @click="handleButtonClick(record.cb_id)">查看</a-button>
            <a-button size="small" type="primary" @click="handleMenuClick('1', record.cb_id)">下载</a-button>
            <a-button size="small" type="primary"  @click="handleMenuClick('2', record.cb_id)">上传</a-button>
          </template>
        </s-table>
      </div>
    </a-card>
    <a-modal
      centered
      title="上传材料"
      :confirm-loading="loading"
      v-model="uploadVisible"
      @ok="submitUpload"
    >
      <a-form-model
        :model="uploadForm"
      >
        <a-form-model-item label="业务名称">
          <a-input disabled v-model="uploadForm.business_name" type="text" />
        </a-form-model-item>
        <a-form-model-item label="整理后材料">
          <a-upload
            name="file"
            :multiple="true"
            :headers="headers"
            :action="uploadUrl"
            :show-upload-list="false"
            @change="onChange"
          >
            <a-button type="danger"> <a-icon type="upload" />上传整理后的材料</a-button>
          </a-upload>
        </a-form-model-item>
        <a-button v-if="uploadForm.mat" size="small" type="link" icon="download" @click="download(uploadForm.mat.file, uploadForm.mat.filename)"><ellipsis :length="30">{{uploadForm.mat.filename}}</ellipsis></a-button>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      title="下载材料"
      v-model="downloadVisible"
    >
      <a-alert>
        <template slot="message">
          <b>整理后的材料：</b><a @click="download(zip.mat, zip.mat_filename)">{{zip.mat_filename}}</a>
        </template>
      </a-alert>
      <a-divider />
      <a-form-model
        ref="downloadForm"
      >
        <a-form-model-item v-for="(item,index) in downloadForm" :key="index">
          <template slot="label"><b>{{item.mat_name}}</b></template>
          <div v-if="item.type == 'image'">
            <div v-if="item.value != ''">
              <img style="width: 100%" :src="item.value"/>
            </div>
            <div v-else>无</div>
          </div>
          <div v-else-if="item.type == 'file'">
            <div v-if="item.value != ''">
              <a-button size="small" type="link" icon="download" @click="download(item.value, item.filename)">{{item.filename}}</a-button>
            </div>
            <div v-else>无</div>
          </div>
          <div v-else>
            <div v-if="item.value != ''">
              {{item.value}}
            </div>
            <div v-else>无</div>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      v-model="historyVisible"
      title="历史信息"
      :footer="null"
    >
      <a-timeline>
        <a-timeline-item v-for="(item, index) in historyData" :key="index">
          {{item.step}}{{item.username}},{{item.notes}} {{item.created_at}}
        </a-timeline-item>
      </a-timeline>
    </a-modal>
    <a-modal
      centered
      v-model="submitVisible"
      title="编辑状态"
      @ok="submitChangeStatus"
      @cancel="onCancel"
    >
      <a-form-model
        ref="ruleForm"
        :model="changeStatusForm"
      >
        <a-form-model-item prop="status2">
          <a-radio-group v-model="changeStatusForm.status2" @change="onChangeStatus">
            <a-radio :disabled="index == 34" v-for="(item, index) in changeStatusOpts" :key="index" :value="index">
              {{item}}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item prop="notes">
          <a-textarea :rows="4" v-model="changeStatusForm.notes" placeholder="备注：材料反馈，请填写原因，不能为空"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import Clipboard from 'clipboard'
import { STable, Ellipsis } from '@/components'
import { getLicenseList, getTrademarkHistory, getEditLicenseStatus, postArrangeLicenseStatus, getLicenseDownload, getLicenseUpload, postLicenseUpload } from '@/api/tm.process'
import trademarkColumns from '@/columns/tm.process'
import apis from '@/api'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  components: {
    Ellipsis,
    STable
  },
  name: 'LicenseList',
  data () {
    return {
      advanced: true,
      queryParam: {},
      licenseColumns: trademarkColumns.license,
      historyVisible: false,
      submitVisible: false,
      uploadVisible: false,
      downloadVisible: false,
      historyData: {},
      uploadForm: {},
      downloadForm: {},
      statusOpts: {},
      licenseData: parameters => {
        return getLicenseList(Object.assign(parameters, this.queryParam)).then(res => {
          this.statusOpts = res.result.status2_opts
          return res.result
        })
      },
      searchSource: [],
      changeStatusForm: {},
      changeStatusOpts: {},
      zip: {},
      uploadUrl: apis.Upload,
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      loading: false
    }
  },
  methods: {
    changeStatus (id) {
      const app = this
      app.changeStatusForm = {}
      app.changeStatusForm['cb_id'] = id
      getEditLicenseStatus(id).then(res => {
        if (res.status === 0) {
          app.changeStatusOpts = res.result.status2_items
          app.changeStatusForm.notes = res.result.contract_business.notes
          app.submitVisible = true
        } else {
          app.$warning({
            title: res.msg
          })
          return false
        }
      })
    },
    submitChangeStatus () {
      const app = this
      const data = {}
      data['contract_business[status2]'] = app.changeStatusForm.status2
      data['contract_business[notes]'] = app.changeStatusForm.notes
      postArrangeLicenseStatus(app.changeStatusForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.onCancel()
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    onCancel () {
      this.changeStatusForm = {}
      this.submitVisible = false
    },
    onChangeStatus (e) {
      this.changeStatusForm.status2 = e.target.value
    },
    historyModal (id) {
      const app = this
      getTrademarkHistory(id).then(res => {
        if (res.status === 0) {
          app.historyData = res.result.data
          app.historyVisible = true
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    handleButtonClick (id) {
      this.$router.push({ name: 'TrademarkEdit', params: { id } })
    },
    handleMenuClick (e, id) {
      console.log(e)
      if (e === '1') {
        this.onDownload(id)
      } else if (e === '2') {
        this.onUpload(id)
      }
    },
    onDownload (id) {
      this.downloadForm = {}
      getLicenseDownload(id).then(res => {
        this.downloadForm = res.result.data
        this.zip['mat'] = res.result.mat
        this.zip['mat_filename'] = res.result.mat_filename
        this.downloadVisible = true
      })
    },
    onUpload (id) {
      const app = this
      app.uploadForm = {}
      getLicenseUpload(id).then(res => {
        if (res.status === 0) {
          app.uploadForm = res.result
          app.uploadForm['cb_id'] = id
          app.uploadVisible = true
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return false
      }
      if (info.file.status === 'done') {
        this.uploadForm.mat.filename = info.file.name
        this.uploadForm.mat.file = info.file.response.result.url
        this.loading = false
      }
    },
    submitUpload () {
      const app = this
      const data = {}
      data['mat[file]'] = app.uploadForm.mat.file
      data['mat[filename]'] = app.uploadForm.mat.filename
      postLicenseUpload(app.uploadForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.uploadVisible = false
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    download (value, filename) {
      window.open(apis.Download + '?value=' + value + '&filename=' + filename)
    },
    copy () {
      const clipboard = new Clipboard('.copy')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
      })
      clipboard.on('error', e => {
        this.$message.error('复制失败')
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    reset () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    onChangeTime (date, dateString) {
      this.queryParam['filter[open_time_start]'] = dateString[0]
      this.queryParam['filter[open_time_end]'] = dateString[1]
    }
  }
}
</script>

<style scoped>
/deep/.table-operator button{margin-right: 0;}
</style>
